package com.szp.lagou.dubbo.filerDemo.filter;

import com.szp.lagou.dubbo.filerDemo.Context.IpContext;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Activate(group = {CommonConstants.CONSUMER})//,CommonConstants.PROVIDER
public class TransportIPFilter implements Filter, HandlerInterceptor {
    public final static String CLIENT_IP_KEY = "client";
    Logger logger = LoggerFactory.getLogger(TransportIPFilter.class);
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String clientIp = IpContext.getContext().getClientIp();
        RpcContext.getContext().getAttachments().put(CLIENT_IP_KEY, clientIp);
        logger.info("filter设置clientIp{}"+ clientIp);
        try {
            // 执行方法
            return  invoker.invoke(invocation);
        }catch (Exception e){
            logger.error("使用dubbo进行远程调用失败!");
            return null;
        }
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String clientIp = request.getRemoteAddr();
        IpContext.getContext().setClientIp(clientIp);
        return true;
    }
}
